﻿using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Microsoft.Playwright;

namespace Jy.Abp.Playwright;

public static class IPlaywrightProviderExtensions 
{
    private readonly static ConcurrentDictionary<string, Lazy<Task<BrowserContextCacheItem>>> _cachedContexts = new ConcurrentDictionary<string, Lazy<Task<BrowserContextCacheItem>>>();

    /// <summary>
    /// 获取一个<see cref="IBrowserContext" />的临时缓存对像
    /// 当缓存存在时新的请求直接返回缓存
    /// 当<see cref="BrowserContextCacheItem"/>释放时清除缓存
    /// </summary>
    public static async Task<BrowserContextCacheItem> GetCachedContextAsync(
        this IPlaywrightProvider provider,
        string key, 
        BrowserNewContextOptions options = null)
    {
        return await _cachedContexts
            .GetOrAdd(
               key: key,
               value: new Lazy<Task<BrowserContextCacheItem>>
               (
                 async () =>
                 {
                     var context = await provider.GetContextAsync(options);
                     context.Close += (o, e) =>
                        _cachedContexts.TryRemove(key, out var item);
                     return new BrowserContextCacheItem(key, context);
                 },
                 true
               )
            )
            .Value;
    }
}
